var loaderUtils = require('loader-utils')

module.exports = function (source) {
    let options = loaderUtils.getOptions(this) || {}

    let { root = '/@root/', newRoot = '/', patterns = [] } = options

    if (this.cacheable) {
        this.cacheable();
    }

    if (Array.isArray(patterns) && patterns.length > 0) {

        let tempSource = source

        for (let i = 0; i < patterns.length; i++) {
            let { root = '/@root/', newRoot = '/' } = patterns[i] || {}

            let globalRegExp = new RegExp(root, 'g')

            if (globalRegExp.test(source)) {
                tempSource = tempSource.replace(globalRegExp, newRoot)
            }
        }

        return tempSource

    } else {

        let globalRegExp = new RegExp(root, 'g')

        if (globalRegExp.test(source)) {
            return source.replace(globalRegExp, newRoot)
        } else {
            return source
        }
    }
}